package com.senlin.ethereum.core;

import java.util.concurrent.*;

public class EthEventLoop {
    private final ExecutorService threadPool;
    private final int threads = Runtime.getRuntime().availableProcessors() + 1;
    private final int workQueueSize = 10000;

    private EthEventLoop() {
        this.threadPool = this.defaultThreadPool();
    }
    public static EthEventLoop current() {
        return new EthEventLoop();
    }

    private ThreadPoolExecutor defaultThreadPool() {
        return new ThreadPoolExecutor(
                threads,
                threads,
                0L,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue(workQueueSize),
                new EthEventLoop.EthPolicy()
        );
    }

    public void asyncConsume(Runnable runnable) {
        this.threadPool.execute(runnable);
    }

    public static class EthPolicy implements RejectedExecutionHandler {
        public EthPolicy() {}

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() + " rejected from " + e.toString());
        }
    }
}
